package com.agileboot.admin.controller.common;

import com.agileboot.common.core.dto.ResponseDTO;
import com.agileboot.common.utils.poi.ExportImportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 通用数据导入导出控制器
 *
 * @author agileboot
 */
@Tag(name = "通用导入导出接口")
@RestController
@RequestMapping("/common/import-export")
@RequiredArgsConstructor
@Slf4j
public class ExportImportController {

    @NonNull
    private final ExportImportService exportImportService;

    /**
     * 导出数据模板
     *
     * @param className 类名
     * @param response HTTP响应
     * @param fileExtension 文件扩展名
     */
    @Operation(summary = "获取导入模板")
    @GetMapping("/template/{className}")
    public void getImportTemplate(
            @Parameter(description = "类名") @PathVariable String className,
            @Parameter(description = "文件扩展名(excel/csv)") @RequestParam(defaultValue = "excel") String fileExtension,
            @Parameter(description = "模板名称") @RequestParam(required = false) String templateName,
            HttpServletResponse response) {
        try {
            // 获取类对象
            Class<?> clazz = Class.forName(className);
            // 导出模板
            exportImportService.getImportTemplate(clazz, response, templateName, fileExtension);
        } catch (ClassNotFoundException e) {
            log.error("找不到指定的类：{}", className, e);
            // 此处不需要返回值，只需要记录错误
        }
    }

    /**
     * 导入数据
     *
     * @param file 上传的文件
     * @param className 目标类名
     * @return 导入的数据列表
     */
    @Operation(summary = "导入数据")
    @PostMapping("/import/{className}")
    public ResponseDTO<List<?>> importData(
            @Parameter(description = "上传的文件") MultipartFile file,
            @Parameter(description = "类名") @PathVariable String className) {
        try {
            // 获取类对象
            Class<?> clazz = Class.forName(className);
            // 导入数据
            List<?> dataList = exportImportService.importData(file, clazz);
            return ResponseDTO.ok(dataList);
        } catch (ClassNotFoundException e) {
            log.error("找不到指定的类：{}", className, e);
            // 返回一个空列表，以确保类型匹配
            return ResponseDTO.fail(Collections.emptyList());
        }
    }
} 